package edu.whu.controller;

import edu.whu.entity.Product;
import edu.whu.service.ProductService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("products")
@Tag(name="product controller", description = "商品管理")
public class ProductController {

    @Autowired
    ProductService productService;

    @GetMapping("/{id}")
    @ApiOperation("根据商品id查找商品")
    public ResponseEntity<Product> getProduct(@ApiParam("商品id") @PathVariable long id){
        Product result = productService.getProduct(id);

        if(result == null){
            return ResponseEntity.noContent().build();
        }
        else{
            return ResponseEntity.ok(result);
        }
    }

    @ApiOperation("获得商品列表")
    @GetMapping("")
    public ResponseEntity<List<Product>> findProducts(@ApiParam("商品名称") String name, @ApiParam("商品价格") Double price){
        List<Product> result = productService.findProduct(name, price);
        return ResponseEntity.ok(result);
    }

    @ApiOperation("添加商品")
    @PostMapping("")
    public ResponseEntity<Product> addProduct(@RequestBody Product product){
        Product result = productService.addProduct(product);
        return ResponseEntity.ok(result);
    }

    @ApiOperation("修改商品信息")
    @PutMapping("/{id}")
    public ResponseEntity<Void> updateProduct(@PathVariable long id, @RequestBody Product product){
        try{
            productService.updateProduct(id, product);
            return ResponseEntity.ok().build();
        }
        catch (NullPointerException e){
            return ResponseEntity.noContent().build();
        }
    }

    @ApiOperation("删除商品")
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delProduct(@PathVariable long id){
        productService.deleteProduct(id);
        return ResponseEntity.ok().build();
    }
}
